package cn.portx.view;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf3.dorado.jpa.JpaUtil;
import com.bstek.bdf3.dorado.jpa.policy.SaveContext;
import com.bstek.bdf3.dorado.jpa.policy.impl.SmartSavePolicyAdapter;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

import cn.portx.entity.Car;
import cn.portx.entity.Fleet;

@Component
public class FleetPR {

	@DataProvider
	@Transactional(readOnly = true)
	public void loadFleets(Page<Fleet> page, Criteria criteria) {
		JpaUtil.linq(Fleet.class).where(criteria).paging(page);
	}

	@DataProvider
	@Transactional(readOnly = true)
	public void loadCars(Page<Car> page, Criteria criteria, String fleetId) {
		JpaUtil.linq(Car.class).equal("fleetId", fleetId).where(criteria).paging(page);
	}

	@DataResolver
	@Transactional
	public void saveFleets(List<Fleet> list) {
		JpaUtil.save(list, new SmartSavePolicyAdapter() {
			@Override
			public boolean beforeInsert(SaveContext context) {
				Object parent = context.getParent();
				Object entity = context.getEntity();
				if (parent instanceof Fleet && entity instanceof Car) {
					((Car) entity).setFleetId(((Fleet) parent).getId());
				}
				return true;
			}
		});
	}
}
